package com.nmgs.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.List;

public class ExcelImportUtil {

    /**
     * 导出数据到excel文件返回到前端浏览器
     * @param filename  文件名
     * @param dataResult    源数据
     * @param clazz 数据类
     * @param toFilePath    本地路径
     */
    public static void exportExcelToLocal(String filename, List<?> dataResult, Class<?> clazz, String toFilePath) {
        OutputStream outputStream = null;
        ExcelWriter excelWriter = null;
        try {
            if (StringUtils.isBlank(filename)) {
                throw new RuntimeException("'filename' 不能为空");
            }
            String fileName = filename.concat(".xlsx");

            // 将文件输出到指定路径
            File file = new File(toFilePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String filePath = toFilePath + File.separator + fileName;
            outputStream = new FileOutputStream(filePath);

            // 根据不同的策略生成不同的ExcelWriter对象
            excelWriter = getExportExcelWriter(outputStream);

            WriteTable writeTable = EasyExcel.writerTable(0).head(clazz).needHead(true).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(fileName).build();
            // 写出数据
            excelWriter.write(dataResult, writeSheet, writeTable);

        } catch (Exception e) {
            LogUtil.error("导出excel数据异常："+e.getMessage(),ExcelImportUtil.class);
            throw new RuntimeException(e);
        }
    }

    private static ExcelWriter getExportExcelWriter(OutputStream outputStream) {
        return EasyExcel.write(outputStream).build();
    }
}


